package com.hotel.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hotel.dao.user.UserMapper;
import com.hotel.entity.Function;
import com.hotel.entity.User;
import com.hotel.security.model.LoginUser;
import com.hotel.service.user.UserService;
import com.hotel.service.user.impl.UserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserLoginName, loginName);
        User user = userMapper.selectOne(wrapper);
        //如果查询不到数据就通过抛出异常来给出提示
        if (Objects.isNull(user)) {
            throw new RuntimeException("user password error");
        }
        //TODO 根据用户查询权限信息 添加到LoginUser中
        //List<String> menus =userService.getBtnStrArrById(user.getId());
        List<Function> functions = null;
        functions = userService.getUserBtnStrById(user.getUserId());
        //List<String> list = new ArrayList<>(Arrays.asList("test","admin"));
        //封装成UserDetails对象返回
        return new LoginUser(user, functions);
    }
}
